import React, {Component} from 'react';
// import "./index.less"
import "./index.css"
import {Button, Form, Input, message, Radio, Select} from 'antd';
import {AxioInstance} from "../../api/AxiosHelper";
import {
    BIND_STUDENT,
    BIND_TEACHER,
    GET_CLASSES_ALL,
    GET_COLLEGE_LIST,
    GET_MAJOR_ALL,
    GET_SCHOOL_LIST,
    SERACH_COLLEGE
} from "../../api/APIURLDefine";
import {FormInstance} from "antd/es/form";
import {withRouter} from 'react-router-dom';
import {inject, observer} from "mobx-react";

const layout = {
    labelCol: {span: 8},
    wrapperCol: {span: 16},
};
const tailLayout = {
    wrapperCol: {offset: 8, span: 16},
};
const {Option} = Select;

/*身份认证界面*/

// @ts-ignore
@withRouter
@inject("globalStore", "userStore")
@observer
class Authentication extends Component<any, any> {
    constructor(props) {
        super(props);
        this.state = {
            value: 1,
            college: [],
            major: [],
            classes: [],
            review: false,
            school: []
        }
    }

    async componentDidMount() {
        this.GetSchoolList("");
        //跳转后滑动条置顶
        document.getElementById("authenticate").scrollIntoView();
        this.props.globalStore.SetShowSearch(false);
        await this.props.userStore.ReloadUserInfo();
        const msg = this.props.userStore.userInfo.additionalData;
        if (msg && msg.state === 1) {
            this.props.history.push("/view");
        }
        console.log(msg)
        this.formInstance?.setFieldsValue({
            name: msg?.name,
            teacherId: msg?.teacherId,
            description: msg?.description,
            studentId: msg?.studentId,
            trueName: msg?.truename,
            college: msg?.college ? msg.college.name : null,
            school: msg?.school ? msg.school.name : null,
            major: msg?.major ? msg.major.name : null,
            classId: msg?.class ? msg.class.name : null
        });
    }

    componentWillUnmount() {
        this.props.globalStore.SetShowSearch(true);
    }

    onFinish = values => {
        console.log('Success:', values);
        let path = "";
        if (this.state.value === 1) {
            path = BIND_STUDENT;
        } else {
            path = BIND_TEACHER;
        }
        AxioInstance.post(path, values).then((data) => {
            console.log(data);
            message.success("提交成功，等待后台审核");
        }).then(async () => {
            await this.props.userStore.ReloadUserInfo();
            const msg = this.props.userStore.userInfo.additionalData;
            if (msg && msg.state === 1) {
                this.props.history.push("/view");
            }
            this.formInstance?.setFieldsValue({
                name: msg?.name,
                teacherId: msg?.teacherId,
                description: msg?.description,
                studentId: msg?.studentId,
                trueName: msg?.truename,
                college: msg?.college ? msg.college.name : null,
                school: msg?.school ? msg.school.name : null,
                major: msg?.major ? msg.major.name : null,
                classId: msg?.class ? msg.class.name : null
            });
        }).catch((e) => {
            message.error("绑定失败");
            //清空表单内容
            this.formInstance.setFieldsValue({
                name: "",
                teacherId: "",
                description: "",
                studentId: "",
                trueName: "",
                college: "",
                major: "",
                classId: ""
            });
        })
    };
    formInstance: FormInstance = null
    onFinishFailed = errorInfo => {
        console.log('Failed:', errorInfo);
    };
    onChange = e => {
        this.setState({value: e.target.value});
    };
    onSearch = (value) => {
        if (value === "") {
            this.GetSchoolList("");
        } else {
            AxioInstance.get(`${GET_SCHOOL_LIST}?key=${value}`).then((data: any) => {
                this.setState({school: data});
            }).catch((e) => {
                console.error(e);
                this.setState({school: []});
            });
        }
    }

    GetCollegeList(value) {
        AxioInstance.get(`${GET_COLLEGE_LIST}/${value}`).then((data: any) => {
            this.setState({college: data});
        }).catch((e) => {
            console.error(e);
            this.setState({college: []});
        });
    }

    GetMajorList(value) {
        this.setState({major: [], classes: []});
        AxioInstance.get(`${GET_MAJOR_ALL}/${value}`).then((data: any) => {
            this.setState({major: data});
            if (data === []) {
                this.formInstance.setFieldsValue({major: "", _class: ""});
            }
        }).catch((e) => {
            console.error(e);
            this.setState({major: []});
        });
    }

    GetSchoolList(value) {
        this.setState({major: [], classes: []});
        AxioInstance.get(`${GET_SCHOOL_LIST}?key=${value}`).then((data: any) => {
            this.setState({school: data});
            if (data === []) {
                this.formInstance.setFieldsValue({major: "", _class: ""});
            }
        }).catch((e) => {
            console.error(e);
            this.setState({school: []});
        });
    }


    private GetClassesList(value: any) {
        this.setState({classes: []});
        AxioInstance.get(`${GET_CLASSES_ALL}/${value}`).then((data: any) => {
            this.setState({classes: data});
        }).catch((e) => {
            console.error(e);
            this.setState({classes: []});
        });
    }

    render() {
        const self = this.state;
        const review = this.props.userStore.userInfo?.additionalData && this.props.userStore.userInfo.additionalData.state === 2;
        return (
            <div className="auth-back" id="authenticate">
                <div className="auth-view">
                    <div className="auth-head">
                        <Radio.Group onChange={this.onChange} value={self.value}>
                            <Radio style={{marginRight: "0.95rem"}} value={1}>学生</Radio>
                            <Radio value={2}>教师</Radio>
                        </Radio.Group>
                    </div>
                    <div className="auth-form">
                        <Form
                            ref={(form) => this.formInstance = form}
                            name="basic"
                            initialValues={{remember: true}}
                            onFinish={this.onFinish}
                            onFinishFailed={this.onFinishFailed}
                        >
                            <Form.Item
                                label={self.value === 1 ? "学号" : "工号"}
                                name={self.value === 1 ? "studentId" : "teacherId"}
                                rules={[{required: true, message: ``}]}
                            >
                                <Input disabled={review} className="auth-input"/>
                            </Form.Item>

                            <Form.Item
                                label="姓名"
                                name={self.value === 1 ? "trueName" : "name"}
                                rules={[{required: true, message: ''}]}
                            >
                                <Input disabled={review} className="auth-input"/>
                            </Form.Item>
                            {
                                self.value === 2 ?
                                    <Form.Item
                                        label="描述"
                                        name="description"
                                        rules={[{required: true, message: ''}]}
                                    >
                                        <Input disabled={review} className="auth-input"/>
                                    </Form.Item>
                                    : null
                            }
                            {
                                self.value === 1 ?
                                    <div>
                                        <Form.Item label="学校" name="school"
                                                   rules={[{required: true, message: ''}]}>
                                            <Select
                                                showSearch
                                                disabled={review}
                                                className="auth-select"
                                                placeholder="请选择学校"
                                                onSearch={this.onSearch.bind(this)}
                                                onChange={(value, ele: any) => {
                                                    this.formInstance.setFieldsValue({
                                                        college: "",
                                                        major: "",
                                                        _class: ""
                                                    });
                                                    this.GetCollegeList(ele.key);
                                                }}
                                            >
                                                {
                                                    self.school.map((element, index) => {
                                                        return <Option key={element.id}
                                                                       value={element.name}>{element.name}</Option>
                                                    })
                                                }
                                            </Select>
                                        </Form.Item>
                                        <Form.Item label="院系" name="college"
                                                   rules={[{required: true, message: ''}]}>
                                            <Select
                                                showSearch
                                                disabled={self.college.length <= 0 || review}
                                                className="auth-select"
                                                placeholder="请选择院系"
                                                onSearch={this.onSearch.bind(this)}
                                                onChange={(value, ele: any) => {
                                                    this.formInstance.setFieldsValue({major: "", _class: ""});
                                                    this.GetMajorList(ele.key);
                                                }}
                                            >
                                                {
                                                    self.college.map((element, index) => {
                                                        return <Option key={element.id}
                                                                       value={element.collegeName}>{element.collegeName}</Option>
                                                    })
                                                }
                                            </Select>
                                        </Form.Item>
                                        <Form.Item label="专业" name="major"
                                                   rules={[{required: true, message: ''}]}>
                                            <Select
                                                className="auth-select"
                                                disabled={self.major.length <= 0 || review}
                                                placeholder="请选择专业"
                                                onChange={(value) => {
                                                    this.formInstance.setFieldsValue({_class: ""});
                                                    this.GetClassesList(value);
                                                }}
                                            >
                                                {
                                                    self.major.map((element, index) => {
                                                        return <Option key={index}
                                                                       value={element.id}>{element.majorName}</Option>
                                                    })
                                                }
                                            </Select>
                                        </Form.Item>
                                        <Form.Item label="班级" name="classId"
                                                   rules={[{required: true, message: ''}]}>
                                            <Select
                                                className="auth-select"
                                                disabled={self.classes.length <= 0 || self.major.length <= 0 || review}
                                                placeholder="请选择班级"
                                            >
                                                {
                                                    self.classes.map((element, index) => {
                                                        return <Option key={index}
                                                                       value={element.id}>{`${element.grade}年级${element.classIndex}班`}</Option>
                                                    })
                                                }
                                            </Select>
                                        </Form.Item>
                                    </div>
                                    : null
                            }
                            <Form.Item>
                                <button disabled={review} className="form-Button"
                                        type={"submit"}>
                                    {review ? "正在审核中" : "验证"}
                                </button>
                            </Form.Item>
                        </Form>
                    </div>
                </div>
            </div>
        );
    }


}

export default Authentication;